#include "stream.h"
#include "ssiot/ssiot.h"
#include "ssiot/settings.h"
#include "stream/rtsp.h"

#include <chrono>
#include <thread>

Stream::Stream()
{
}

Stream::~Stream()
{
}

int Stream::Init(void)
{
	nlohmann::json cfg;

	cfg["rtsp"] = "rtsp://admin:wuhan2019@172.16.22.238:554/h264/ch1/sub/av_stream";
	cfg["motion"] = 30;
	cfg["recsize"] = 240;
	cfg["conf"] = 0.5;
	cfg["nms"] = 0.4;
	cfg["width"] = 0;
	cfg["height"] = 0;
	cfg["target"] = "CPU";
		
	cfg["sn"] = SSIoT::INST()->SN();

	SSIoT::INST()->settings()->LoadSettings("stream", cfg);
	SSIoT::INST()->settings()->SyncSettings("stream", cfg);


	fprintf(stdout, "stream config: \n%s\n", cfg.dump().c_str());

	Rtsp rtsp;

	for (int i = 0; i < 1000; i++) {
		rtsp.Close();

		if (rtsp.Open(cfg) != 0) {
			fprintf(stderr, "rtsp open error.\n");
			std::this_thread::sleep_for(std::chrono::seconds(i%10));
			continue;
		}
		try
		{
			rtsp.Play();
		}
		catch (...) {
			fprintf(stderr, "play error.\n");
		}
	}
	
	rtsp.Close();

	return 0;
}

void Stream::Fini(void)
{

}
